//
//  HoroRequest.m
//  SubscribeBase
//
//  Created by changshuai on 2018/7/14.
//  Copyright © 2018年 changshuai. All rights reserved.
//

#import "HoroRequest.h"
#import "HoroModel.h"
#import "MJExtension.h"
#import "AFNetworking.h"
#import "Util.h"
#import "AppState.h"

#define HoroUrl @"http://web.juhe.cn:8080/constellation/getAll?consName=%@&type=%@&key=ff20be62a2d9f9b944443352ac07bf02"


#define horoAliURL @"http://horo.xiongx.net:8002/horodata/%@/%@/%@";


@implementation HoroRequest

+(void)GetAppInfoCompletion:(CCDoneBlock)onCompletion
                      onError:(CCErrorBlock)onError
{
    [HoroRequest httpGet:CC_VSTATE_URL onCompletion:^(id result) {
        if([result isKindOfClass:[NSDictionary class]]){
            AppStateInstance.versionCode = [[(NSDictionary *)result objectForKey:@"version_code"] integerValue];
            if(onCompletion) {
                onCompletion(@"1");
            }
            
        }else{
            if (onError) {
                onError([NSError new]);
            }
        }
    } onError:^(NSError *error) {
        if (onError) {
            onError([NSError new]);
        }
    }];
}


+ (void) getData:(NSString*)name withType:(NSString*)type onCompletion:(CCDoneBlock)onCompletion
         onError:(CCErrorBlock)onError {
    
    NSString *url = [NSString stringWithFormat:HoroUrl, name, type];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]  cachePolicy:1  timeoutInterval:10];
    NSURLSession *requestSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [requestSession dataTaskWithRequest:request
       completionHandler:^(NSData * _Nullable body , NSURLResponse * _Nullable response, NSError * _Nullable error)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error) {
                    onError(error);
                    NSLog(@"NSURLSessionDataTaskerror:%@",error);
                } else {
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:body options:NSJSONReadingMutableContainers error:nil];
                    NSLog(@"NSURLSessionDataTaskdic:%@",dic);
                    if([[dic objectForKey:@"error_code"] intValue] == 0) {
//                        NSDictionary* result = [dic objectForKey:@"result"];
                        HoroModel* model = [HoroModel mj_objectWithKeyValues:dic];
                        NSLog(@"model:%@",model.summary);
                        onCompletion(model);
                    } else {
                        onError([NSError new]);
                    }
                }
                
            });
        }];
        [task resume];
}

+ (void) getData:(NSString*)name withDate:(NSString*)date onCompletion:(CCDoneBlock)onCompletion
         onError:(CCErrorBlock)onError {
    
    NSString* str = [NSString stringWithFormat:@"%@%@%@",name,date,@"1opVOGROwKJ64QYZ"];
    
    NSString *sign = [Util md5:str];
    
    NSString *url = horoAliURL;
    
    url = [NSString stringWithFormat:url,name,date,sign];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]  cachePolicy:1  timeoutInterval:10];
    NSURLSession *requestSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [requestSession dataTaskWithRequest:request
                                                   completionHandler:^(NSData * _Nullable body , NSURLResponse * _Nullable response, NSError * _Nullable error)
                                  {
                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          if (error) {
                                              onError(error);
                                              NSLog(@"NSURLSessionDataTaskerror:%@",error);
                                          } else {
                                              NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:body options:NSJSONReadingMutableContainers error:nil];
                                              NSLog(@"NSURLSessionDataTaskdic:%@",dic);
                                              if([[dic objectForKey:@"code"] intValue] == 0) {
                                                  NSDictionary* result = [dic objectForKey:@"data"];
                                                  HoroModel* model = [HoroModel mj_objectWithKeyValues:result];
                                                  NSLog(@"model:%@",model.summary);
                                                  onCompletion(model);
                                              } else {
                                                  onError([NSError new]);
                                              }
                                          }
                                          
                                      });
                                  }];
    
    [task resume];
}

+ (void) getEnglishFromChinese :(NSString*)chinese onCompletion:(CCDoneBlock)onCompletion
        onError:(CCErrorBlock)onError {
    //申请的 appId
    NSString *appId = @"20180716000185995";
    //随机数
    NSString *salt = @"1435660288";
    //密钥
    NSString *pass = @"QESFph6cO9bOe9EFFobm";
    
    //拼接字符串
    NSString *string = [NSString stringWithFormat:@"%@%@%@%@", appId, chinese, salt, pass];
    //UTF8 编码
    NSString *String = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //加密
    NSString *sign = [Util md5:String];
    
    //对 q 进行 编码 (第二次使用)
    NSString *qEncoding = [chinese stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *httpStr = @"http://api.fanyi.baidu.com/api/trans/vip/translate";
    //拼接 URL
    NSString *urlStr = [NSString stringWithFormat:@"%@?q=%@&from=%@&to=%@&appid=%@&salt=%@&sign=%@",
                        httpStr,
                        qEncoding,
                        @"auto",
                        @"en",
                        appId,
                        salt,
                        sign];
    
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                onError(error);
            } else {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSString* resStr = [[dic objectForKey:@"trans_result"] firstObject][@"dst"];
                NSLog(@"resStr: %@", resStr);
                onCompletion(resStr);
            }
        });
    }];
    
    //开启任务
    [task resume];
}

+ (void) httpGet:(NSString*)url onCompletion:(CCDoneBlock)onCompletion
         onError:(CCErrorBlock)onError {
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]  cachePolicy:1  timeoutInterval:10];
    NSURLSession *requestSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [requestSession dataTaskWithRequest:request
                                                   completionHandler:^(NSData * _Nullable body , NSURLResponse * _Nullable response, NSError * _Nullable error)
                                  {
                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          if (error) {
                                              onError(error);
                                              NSLog(@"NSURLSession error:%@",error);
                                          } else {
                                              NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:body options:NSJSONReadingMutableContainers error:nil];
                                              NSLog(@"NSURLSession data:%@",dic);
                                              onCompletion(dic);
                                          }
                                      });
                                  }];
    
    [task resume];
}

@end
